package com.example.bledemo.ui.view;

import android.app.AlertDialog;
import android.content.Context;
import android.content.DialogInterface;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.graphics.Canvas;
import android.graphics.Color;
import android.graphics.Paint;
import android.graphics.Rect;
import android.graphics.Typeface;
import android.util.AttributeSet;
import android.util.Log;
import android.view.View;
import android.widget.Toast;

import java.io.IOException;
import java.io.InputStream;

/**
 * 自定义地图点位标注View
 * 用于在地图上显示带有标题的点位标记
 */
public class MyMapPointWithTitleView extends View {
    
    // 点位类型常量
    public static final int RED_POINT = 0;
    public static final int BLUE_POINT = 1;
    public static final int GRAY_POINT = 2;
    public static final int BLACK_POINT = 3;
    public static final int PEOPLE_POINT = 4;
    public static final int DEFAULT_POINT = 5;
    
    // 点位属性
    private int pointType = BLUE_POINT;
    private String pointTitle = "";
    private boolean showTitle = true;
    
    // 绘制相关
    private Paint pointPaint;
    private Paint titlePaint;
    private Paint backgroundPaint;
    private Bitmap pointIcon;
    
    // 尺寸相关
    private int pointSize = 24; // 点位图标大小
    private int titlePadding = 8; // 标题内边距
    private int titleMargin = 4; // 标题与图标的间距
    private int cornerRadius = 6; // 标题背景圆角半径
    
    // 位置信息
    private double originalX;
    private double originalY;
    
    // 导航回调接口
    public interface OnNavigationListener {
        void onNavigate(String pointTitle, double x, double y);
    }
    
    private OnNavigationListener navigationListener;
    
    public MyMapPointWithTitleView(Context context) {
        super(context);
        init();
    }
    
    public MyMapPointWithTitleView(Context context, AttributeSet attrs) {
        super(context, attrs);
        init();
    }
    
    public MyMapPointWithTitleView(Context context, AttributeSet attrs, int defStyleAttr) {
        super(context, attrs, defStyleAttr);
        init();
    }
    
    public MyMapPointWithTitleView(Context context, double x, double y, int type, boolean showTitle, String title) {
        super(context);
        this.originalX = x;
        this.originalY = y;
        this.pointType = type;
        this.showTitle = showTitle;
        this.pointTitle = title != null ? title : "";
        init();
    }
    
    private void init() {
        // 初始化画笔
        initPaints();
        
        // 加载点位图标
        loadPointIcon();
        
        // 设置点击事件
        setOnClickListener(new OnClickListener() {
            @Override
            public void onClick(View v) {
                Log.d("MyMapPointView", "点击了点位: " + pointTitle);
                showNavigationDialog();
            }
        });
    }
    
    private void initPaints() {
        // 点位画笔
        pointPaint = new Paint();
        pointPaint.setAntiAlias(true);
        pointPaint.setStyle(Paint.Style.FILL);
        
        // 标题画笔
        titlePaint = new Paint();
        titlePaint.setAntiAlias(true);
        titlePaint.setColor(Color.WHITE);
        titlePaint.setTextSize(12);
        titlePaint.setTypeface(Typeface.DEFAULT_BOLD);
        
        // 标题背景画笔
        backgroundPaint = new Paint();
        backgroundPaint.setAntiAlias(true);
        backgroundPaint.setColor(Color.parseColor("#80000000")); // 半透明黑色
        backgroundPaint.setStyle(Paint.Style.FILL);
    }
    
    private void loadPointIcon() {
        String iconName = getIconNameByType(pointType);
        try {
            InputStream inputStream = getResources().getAssets().open(iconName);
            pointIcon = BitmapFactory.decodeStream(inputStream);
            inputStream.close();
        } catch (IOException e) {
            Log.e("MyMapPointView", "加载图标失败: " + iconName, e);
            // 如果加载失败，创建一个默认的圆形
            pointIcon = createDefaultPointIcon();
        }
    }
    
    private String getIconNameByType(int type) {
        switch (type) {
            case RED_POINT:
                return "PointIcon_red.png";
            case BLUE_POINT:
                return "PointIcon_blue.png";
            case GRAY_POINT:
                return "PointIcon_gray.png";
            case BLACK_POINT:
                return "PointIcon_black.png";
            case PEOPLE_POINT:
                return "pointIcon_people.png";
            case DEFAULT_POINT:
            default:
                return "PointIcon_default.png";
        }
    }
    
    private Bitmap createDefaultPointIcon() {
        // 创建一个默认的圆形图标
        Bitmap bitmap = Bitmap.createBitmap(pointSize, pointSize, Bitmap.Config.ARGB_8888);
        Canvas canvas = new Canvas(bitmap);
        Paint paint = new Paint();
        paint.setAntiAlias(true);
        paint.setColor(Color.BLUE);
        paint.setStyle(Paint.Style.FILL);
        canvas.drawCircle(pointSize / 2f, pointSize / 2f, pointSize / 2f, paint);
        return bitmap;
    }
    
    @Override
    protected void onMeasure(int widthMeasureSpec, int heightMeasureSpec) {
        int width = pointSize;
        int height = pointSize;
        
        // 如果需要显示标题，计算标题的尺寸
        if (showTitle && !pointTitle.isEmpty()) {
            Rect textBounds = new Rect();
            titlePaint.getTextBounds(pointTitle, 0, pointTitle.length(), textBounds);
            
            int titleWidth = textBounds.width() + titlePadding * 2;
            int titleHeight = textBounds.height() + titlePadding * 2;
            
            width = Math.max(width, titleWidth);
            height += titleHeight + titleMargin;
        }
        
        setMeasuredDimension(width, height);
    }
    
    @Override
    protected void onDraw(Canvas canvas) {
        super.onDraw(canvas);
        
        int centerX = getWidth() / 2;
        int iconY = 0;
        
        // 绘制点位图标
        if (pointIcon != null) {
            int iconX = centerX - pointIcon.getWidth() / 2;
            canvas.drawBitmap(pointIcon, iconX, iconY, null);
        }
        
        // 绘制标题
        if (showTitle && !pointTitle.isEmpty()) {
            drawTitle(canvas, centerX, iconY + pointSize + titleMargin);
        }
    }
    
    private void drawTitle(Canvas canvas, int centerX, int titleY) {
        Rect textBounds = new Rect();
        titlePaint.getTextBounds(pointTitle, 0, pointTitle.length(), textBounds);
        
        int titleWidth = textBounds.width() + titlePadding * 2;
        int titleHeight = textBounds.height() + titlePadding * 2;
        
        // 绘制标题背景
        int bgLeft = centerX - titleWidth / 2;
        int bgTop = titleY;
        int bgRight = bgLeft + titleWidth;
        int bgBottom = bgTop + titleHeight;
        
        canvas.drawRoundRect(bgLeft, bgTop, bgRight, bgBottom, cornerRadius, cornerRadius, backgroundPaint);
        
        // 绘制标题文字
        int textX = centerX - textBounds.width() / 2;
        int textY = titleY + titlePadding + textBounds.height();
        canvas.drawText(pointTitle, textX, textY, titlePaint);
    }
    
    // Getter和Setter方法
    public double getOriginalX() {
        return originalX;
    }
    
    public double getOriginalY() {
        return originalY;
    }
    
    public void setOriginalX(double x) {
        this.originalX = x;
    }
    
    public void setOriginalY(double y) {
        this.originalY = y;
    }
    
    public int getPointType() {
        return pointType;
    }
    
    public void setPointType(int pointType) {
        this.pointType = pointType;
        loadPointIcon();
        invalidate();
    }
    
    public String getPointTitle() {
        return pointTitle;
    }
    
    public void setPointTitle(String title) {
        this.pointTitle = title != null ? title : "";
        requestLayout();
        invalidate();
    }
    
    public boolean isShowTitle() {
        return showTitle;
    }
    
    public void setShowTitle(boolean showTitle) {
        this.showTitle = showTitle;
        requestLayout();
        invalidate();
    }
    
    // 兼容原有接口的方法
    public void setFirstXShow(float x) {
        setX(x);
    }
    
    public void setFirstYShow(float y) {
        setY(y);
    }
    
    public double getFirstX() {
        return originalX;
    }
    
    public double getFirstY() {
        return originalY;
    }
    
    public float getState() {
        return pointType;
    }
    
    public String getTitle() {
        return pointTitle;
    }
    
    /**
     * 设置导航监听器
     */
    public void setOnNavigationListener(OnNavigationListener listener) {
        this.navigationListener = listener;
    }
    
    /**
     * 显示导航对话框
     */
    private void showNavigationDialog() {
        try {
            Context context = getContext();
            if (context == null) {
                Log.e("MyMapPointView", "上下文为空，无法显示对话框");
                return;
            }
            
            AlertDialog.Builder builder = new AlertDialog.Builder(context);
            builder.setTitle("点位操作")
                    .setMessage("你点击了: " + pointTitle + "\n坐标: (" + originalX + ", " + originalY + ")")
                    .setNegativeButton("取消", new DialogInterface.OnClickListener() {
                        @Override
                        public void onClick(DialogInterface dialog, int which) {
                            dialog.dismiss();
                            Log.d("MyMapPointView", "用户点击了取消");
                        }
                    })
                    .setPositiveButton("导航", new DialogInterface.OnClickListener() {
                        @Override
                        public void onClick(DialogInterface dialog, int which) {
                            dialog.dismiss();
                            Log.d("MyMapPointView", "用户点击了导航");
                            if (navigationListener != null) {
                                navigationListener.onNavigate(pointTitle, originalX, originalY);
                            } else {
                                Toast.makeText(context, "导航功能未实现", Toast.LENGTH_SHORT).show();
                            }
                        }
                    });
            
            AlertDialog dialog = builder.create();
            dialog.show();
            
        } catch (Exception e) {
            Log.e("MyMapPointView", "显示对话框失败: " + e.getMessage());
            // 如果对话框显示失败，回退到Toast
            try {
                Toast.makeText(getContext(), pointTitle, Toast.LENGTH_SHORT).show();
            } catch (Exception ex) {
                Log.e("MyMapPointView", "显示Toast也失败: " + ex.getMessage());
            }
        }
    }
}
